import 'package:business_plugin/business/firebase_options.dart';
import 'package:firebase_analytics/firebase_analytics.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_remote_config/firebase_remote_config.dart';
import 'package:flutter/widgets.dart';

/// firebase的api统一初始化
class FirebaseHelper {
  static FirebaseHelper? _instance;

  // 私有的命名构造函数
  FirebaseHelper._internal();

  static FirebaseHelper _getInstance() {
    _instance ??= FirebaseHelper._internal();

    return _instance!;
  }

  late FirebaseApp _firebaseApp;
  late FirebaseAnalytics _analytics;
  late FirebaseRemoteConfig _remoteConfig;

  static bool isInitialized = false;

  static Future<void> init() async {
    if (isInitialized) return;
    final instance = _getInstance();
    //初始化整个 Firebase SDK：这是使用任何 Firebase 服务的前提
    instance._firebaseApp = await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
    //初始化分析服务：设置 Firebase Analytics 用于追踪用户行为
    instance._analytics = FirebaseAnalytics.instanceFor(app: firebaseApp);
    //初始化远程配置：设置 Firebase Remote Config 服务
    instance._remoteConfig = FirebaseRemoteConfig.instanceFor(app: firebaseApp);
    // instance._database = FirebaseDatabase.instanceFor(app: firebaseApp);

    // /// 获取一下远程参数
    // instance._remoteConfig.fetchAndActivate();

    // 设置 Remote Config 参数，fetchTimeout：服务器获取远程配置数据的最大等待时间，minimumFetchInterval：限制每小时最多获取一次新配置
    await instance._remoteConfig.setConfigSettings(RemoteConfigSettings(
      fetchTimeout: const Duration(minutes: 1),
      minimumFetchInterval: const Duration(hours: 1),
    ));

    // 立即获取并激活配置
    await instance._remoteConfig.fetchAndActivate();

    /// 错误上报
    FlutterError.onError = (errorDetails) {
      // FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
    };
    //初始化完成
    isInitialized = true;
  }

  static FirebaseApp get firebaseApp {
    return _getInstance()._firebaseApp;
  }

  static FirebaseAnalytics get analytics {
    return _getInstance()._analytics;
  }

  static FirebaseRemoteConfig get remoteConfig {
    return _getInstance()._remoteConfig;
  }

  // static FirebaseDatabase get database {
  //   return _getInstance()._database;
  // }
}
